package com.helloworld.apps.account.event.spring;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.TaskExecutor;

/**
 * 异步执行的配置
 */
@Configuration
public class AsyncSpringEventsConfig {

    /**
     * 设置为应用上下文的默认事件多播器，这样发布的事件将由配置好的线程池异步执行
     */
    @Bean(name = AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME)
    public ApplicationEventMulticaster simpleApplicationEventMulticaster() {
        SimpleApplicationEventMulticaster eventMulticaster = new SimpleApplicationEventMulticaster();
        eventMulticaster.setTaskExecutor(taskExecutor());
        return eventMulticaster;
    }

    public TaskExecutor taskExecutor() {
        // Spring简单实现
        return new SimpleAsyncTaskExecutor();

        // 自定义线程池 配置线程池参数，比如核心线程数、最大线程数、队列容量等
//        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//        executor.setCorePoolSize(5);
//        executor.setMaxPoolSize(10);
//        executor.setQueueCapacity(20);
//        executor.initialize();
//        return executor;
    }
}
